﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Manyor.Net
{
    /// <summary>
    /// 命令分支器
    /// </summary>
    public class CommandDispatcher
    {
        /// <summary>
        /// 分支器字典
        /// </summary>
        private IDictionary<int, ICommand> _commandDic;

        /// <summary>
        /// 构造器
        /// </summary>
        public CommandDispatcher()
        {
            _commandDic = new Dictionary<int, ICommand>();
        }
        /// <summary>
        /// 注册分支器
        /// </summary>
        /// <param name="commandID"></param>
        /// <param name="cmd"></param>
        public void RegisterCommand(ICommand cmd, int commandID)
        {
            if (_commandDic.ContainsKey(commandID))
            {
                throw new Exception("已包含CommandID:" + commandID);
            }
            else
            {
                _commandDic.Add(commandID, cmd);
            }
        }
        /// <summary>
        /// 注册分支器
        /// </summary>
        /// <param name="cmd"></param>
        /// <param name="commandID"></param>
        public void RegisterCommand(ICommand cmd, params int[] commandID)
        {
            if (commandID.Length == 0)
            {
                throw new Exception("Command不能为空！");
            }
            foreach (int id in commandID)
            {
                RegisterCommand(cmd, id);
            }
        }
        /// <summary>
        /// 解析指定的数据包
        /// </summary>
        /// <param name="commandID">ID</param>
        /// <param name="bytes">字节数组</param>
        /// <param name="length">字节长度</param>
        public void DoTask(byte[] bytes, int length)
        {
            SocketHeader sh = ByteUtility.ConvertHeader(bytes);
            int commandID = sh.CommandField;
            if (!_commandDic.ContainsKey(commandID))
            {
                throw new Exception("无法解析 CommandID:" + commandID);
            }
            else
            {
                ICommand cmd = _commandDic[commandID];
                if (cmd != null)
                {
                    cmd.ExecuteCommand(bytes, length);
                }
            }
        }

    }
}
